package com.mes.check.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.bstek.bdf2.core.orm.ParseResult;
import com.bstek.dorado.data.provider.Page;
import com.mes.basicdata.dao.iface.ITypesDataDao;
import com.mes.check.dao.iface.ICheckTaskDao;
import com.mes.check.domain.CheckTask;
import com.mes.check.domain.CheckTaskAssign;
import com.mes.common.dao.BasicDao;
import com.mes.inventory.dao.iface.IMaterialDao;
import com.mes.inventory.domain.Material;
import com.mes.task.domain.OperationTask;
import com.mes.task.domain.PartTask;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;

@Repository
public class CheckTaskDao extends BasicDao<CheckTask> implements ICheckTaskDao {

	public static final Log log = LogFactory.getLog(CheckTaskDao.class);

	@Autowired
	private IMaterialDao materialDao;
	@Autowired
	private ITypesDataDao typesDataDao;

	@Override
	public void getMaterialReadyCheckTasks(Page<CheckTask> page, Map<String, Object> parameter,
			com.bstek.dorado.data.provider.Criteria criteria) throws Exception {

		Map<String, Object> args = new HashMap<String, Object>();
		StringBuffer coreHql = new StringBuffer("from " + CheckTask.class.getName() + " a "
				+ "where a.checkTaskType in (32, 34) and a.checkTaskState = 205 "
				+ "and (a.operationTask.taskType = '202' and a.operationTask.taskState < 209 or a.operationTask.taskType <> '202') ");

		if (null != parameter && !parameter.isEmpty()) {
			// // 按图号查询
			// String drawingId = (String) parameter.get("drawingId");
			// if (StringUtils.isNotEmpty(drawingId)) {
			// coreHql.append(" and a.part.drawingId like :drawingId ");
			// args.put("drawingId", drawingId + "%");
			// }
			// // 按批次查询
			// String batchNum = (String) parameter.get("batchNum");
			// if (StringUtils.isNotEmpty(batchNum)) {
			// coreHql.append(" and a.operationTask.batchNum like :batchNum ");
			// args.put("batchNum", batchNum + "%");
			// }
			// // 按工序查询
			// String operationIdDesc = (String)
			// parameter.get("operationIdDesc");
			// if (StringUtils.isNotEmpty(operationIdDesc)) {
			// coreHql.append(" and a.operationTask.operationIdDesc =
			// :operationIdDesc ");
			// args.put("operationIdDesc", operationIdDesc);
			// }
			// 任务主制车间
			String deptUid = (String) parameter.get("deptUid");
			if (StringUtils.isNotEmpty(deptUid)) {
				coreHql.append(" and a.operationTask.masterShopUid like :deptUid ");
				args.put("deptUid", deptUid + "%");
			}

		}

		// 根据datagrid的filter中传递来的过滤参数解析hql查询条件
		if (null != criteria) {
			ParseResult result = this.parseCriteria(criteria, true, "a");
			if (null != result) {
				coreHql.append(" and " + result.getAssemblySql());
				args.putAll(result.getValueMap());
			}
		}

		String countHql = "select count(*) " + coreHql.toString();
		String hql = coreHql.toString() + "order by a.operationTask.priority desc, a.operationTask.batchNum";

		Map<String, Object> newArgs = new HashMap<String, Object>();
		String key;
		String newKey;
		Iterator<String> iterator = args.keySet().iterator();
		while (iterator.hasNext()) {
			key = (String) iterator.next();
			newKey = key.replace(".", "_");

			if (key.contains("checkTaskTypeDesc")) {
				newKey = newKey.replace("checkTaskTypeDesc", "checkTaskType");
				String value = (String) args.get(key);
				String checkTaskType = typesDataDao.getTypeIdByTypeName("checktasktype", value.replace("%", ""));
				newArgs.put(newKey, checkTaskType);
			} else if (key.contains("checkTaskStateDesc")) {
				newKey = newKey.replace("checkTaskStateDesc", "checkTaskState");
				String value = (String) args.get(key);
				String checkTaskState = typesDataDao.getTypeIdByTypeName("checktaskstate", value.replace("%", ""));
				newArgs.put(newKey, Integer.valueOf(checkTaskState));
			} else {
				newArgs.put(newKey, args.get(key));
			}

			hql = hql.replace(":" + key, ":" + newKey);
			countHql = countHql.replace(":" + key, ":" + newKey);

			if (key.contains("checkTaskTypeDesc")) {
				hql = hql.replace("checkTaskTypeDesc", "checkTaskType");
				countHql = countHql.replace("checkTaskTypeDesc", "checkTaskType");
			} else if (key.contains("checkTaskStateDesc")) {
				hql = hql.replace("checkTaskStateDesc", "checkTaskState");
				countHql = countHql.replace("checkTaskStateDesc", "checkTaskState");
			}

		}

		this.pagingQuery(page, hql, countHql, newArgs);
	}

	/**
	 * 获取某个检验任务的收料数量
	 * 
	 * @param taskUid
	 * @param checkDeptUid
	 * @return
	 */
	@Override
	public Float getReceivedQty(String taskUid, String checkDeptUid) {
		float receivedQty = 0;

		try {
			Session session = this.getSession();
			String sql = "select nvl(sum(i.invqty),0) from i_invmanage i "
					+ "inner join i_warebin b on i.warehouseid = b.warehouseid and i.binid = b.binid "
					+ "where i.part_number = (select t.part_number from t_tasks t where t.taskuid = ?) "
					+ "and i.batchnum = (select t.batchnum from t_tasks t where t.taskuid = ?"
					+ "and b.deptid like ? || '%')";
			Query query = session.createSQLQuery(sql);
			query.setString(0, taskUid);
			query.setString(1, taskUid);
			query.setString(2, checkDeptUid.substring(0, 4));
			receivedQty = ((java.math.BigDecimal) query.uniqueResult()).floatValue();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return receivedQty;
	}

	/**
	 * 获取某个检验任务的收料数量
	 * 
	 * @param checkTask
	 * @return
	 */
	@Override
	public Float getReceivedQty(CheckTask checkTask) {
		float receivedQty = 0;

		try {
			Session session = this.getSession();
			String sql = "select nvl(sum(i.invqty),0) from i_invmanage i "
					+ "inner join i_warebin b on i.warehouseid = b.warehouseid and i.binid = b.binid "
					+ "where i.part_number = (select t.part_number from t_tasks t where t.taskuid = ?) "
					+ "and i.batchnum = (select t.batchnum from t_tasks t where t.taskuid = ?"
					+ "and b.deptid like ? || '%')";
			Query query = session.createSQLQuery(sql);
			query.setString(0, checkTask.getTaskUid());
			query.setString(1, checkTask.getTaskUid());
			query.setString(2, checkTask.getCheckDeptUid().substring(0, 4));
			receivedQty = ((java.math.BigDecimal) query.uniqueResult()).floatValue();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return receivedQty;
	}

	/**
	 * 获得某个检验任务的已派工数量
	 * 
	 * @param checkTaskUid
	 * @return
	 * @throws Exception
	 */
	@Override
	public Float getDispatchedQty(String checkTaskUid) throws Exception {
		float dispatchedQty = 0;

		Session session = this.getSession();
		String hql = "select nvl(sum(assnQty), 0) from " + CheckTaskAssign.class.getName() + " where checkTaskUid = ?";
		Query query = session.createQuery(hql);
		query.setString(0, checkTaskUid);
		dispatchedQty = ((Double) query.uniqueResult()).floatValue();

		return dispatchedQty;
	}

	@Override
	public List<CheckTask> getMaterialReadyCheckTasks(String checkDeptUid, Page<CheckTask> page) {
		List<CheckTask> list = null;
		try {
			DetachedCriteria crit = DetachedCriteria.forClass(CheckTask.class);
			crit.add(Restrictions.lt("checkTaskState", CheckTask.CHECKTASKSTATE_COMPLETED));
			crit.add(Restrictions.like("checkDeptUid", checkDeptUid, MatchMode.END));
			Integer[] checkTaskTypes = { 32, 33 };
			crit.add(Restrictions.in("checkTaskType", checkTaskTypes));
			crit.add(Restrictions.gt("receivedQty", 0));
			// crit.addOrder(Property.forName("receivedQty").asc());
			if (page != null) {
				this.pagingQuery(page, crit);
			} else {
				list = this.query(crit, null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public List<CheckTask> getSendCheckTasks(String deptUid, Page<CheckTask> page) {
		List<CheckTask> list = null;
		try {
			DetachedCriteria crit = DetachedCriteria.forClass(CheckTask.class);
			crit.add(Restrictions.lt("checkTaskState", CheckTask.CHECKTASKSTATE_COMPLETED));
			crit.add(Restrictions.like("checkDeptUid", deptUid, MatchMode.END));
			Integer[] checkTaskTypes = { 32, 33 };
			crit.add(Restrictions.in("checkTaskType", checkTaskTypes));
			crit.addOrder(Property.forName("actualSend").asc());
			if (page != null) {
				this.pagingQuery(page, crit);
			} else {
				list = this.query(crit, null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public List<CheckTask> getSummaryCheckTasksOfCheckDept(String deptUid, Page<CheckTask> page) {
		List list = null;
		try {
			DetachedCriteria crit = DetachedCriteria.forClass(CheckTask.class);
			crit.add(Restrictions.eq("checkTaskType", CheckTask.CHECKTASKTYPE_SUMMARYCHECK));
			crit.add(Restrictions.ge("checkTaskState", CheckTask.CHECKTASKSTATE_READY));
			crit.add(Restrictions.lt("checkTaskState", CheckTask.CHECKTASKSTATE_COMPLETED));
			crit.add(Restrictions.like("checkDeptUid", deptUid, MatchMode.END));
			crit.addOrder(Property.forName("actualSend").asc());
			if (page != null) {
				this.pagingQuery(page, crit);
			} else {
				list = this.query(crit, null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public List<CheckTask> getComingCheckTasksOfCheckDept(String deptUid, Date beforeDate, Page<CheckTask> page) {
		List list = null;
		try {
			DetachedCriteria crit = DetachedCriteria.forClass(CheckTask.class);
			crit.add(Restrictions.ge("checkTaskState", CheckTask.CHECKTASKSTATE_READY));
			crit.add(Restrictions.lt("checkTaskState", CheckTask.CHECKTASKSTATE_COMPLETED));
			crit.add(Restrictions.like("checkDeptUid", deptUid, MatchMode.END));
			crit.addOrder(Property.forName("actualSend").asc());
			if (page != null) {
				this.pagingQuery(page, crit);
			} else {
				list = this.query(crit, null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public List<CheckTask> getCheckTasksByBarCode(String barCode, String checkDeptUid, Page<CheckTask> page) {
		List list = null;
		try {
			Material material = materialDao.getMaterialByBarcode(barCode);
			if (material != null) {
				list = this.getUnFinishCheckTasks(material.getPartUid(), material.getBatchNum(), checkDeptUid);
			} else {
				log.warn("无法通过条码找对对应物料" + barCode);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public List<CheckTask> getComingCheckTasks(String deptUid, Date beforeDate, Page<CheckTask> page) {
		List list = null;
		try {
			DetachedCriteria crit = DetachedCriteria.forClass(CheckTask.class);

			Integer[] taskStates1 = { 207, 208 };
			Integer[] taskStates2 = { 206, 207, 208, 209 };
			crit.add(
					Restrictions.or(
							Restrictions.and(Restrictions.lt("checkTaskState", CheckTask.CHECKTASKSTATE_COMPLETED),
									Restrictions.and(
											Restrictions.eq("checkTaskType", CheckTask.CHECKTASKTYPE_THIRDCHECK),
											Restrictions.and(Restrictions.like("checkDeptUid", deptUid, MatchMode.END),
													Restrictions.in("operationTask.taskState", taskStates1)))),
							Restrictions.and(Restrictions.lt("checkTaskState", CheckTask.CHECKTASKSTATE_COMPLETED),
									Restrictions.and(
											Restrictions.eq("checkTaskType",
													CheckTask.CHECKTASKTYPE_OPERATIONCHECK),
											Restrictions.and(Restrictions.like("checkDeptUid", deptUid, MatchMode.END),
													Restrictions.and(
															Restrictions.in("operationTask.taskState", taskStates2),
															Restrictions.lt("operationTask.planFinish",
																	beforeDate)))))));
			crit.add(Restrictions.lt("operationTask.device.criticalLevel", 4));
			crit.addOrder(Property.forName("actualSend").asc());
			if (page != null) {
				this.pagingQuery(page, crit);
			} else {
				list = this.query(crit, null);
			}

			// // 流动检验，任务状态为已开始，已暂停
			// hql.append("((checkTaskState<209 and checkTaskType='23' and
			// deptUid like ? || '%' and operationTask.taskState in(207,208))
			// ");
			// // 流动检验
			// hql.append(" or (checkTaskState<209 and checkTaskType='33' and
			// deptUid like ? || '%' and operationTask.taskState
			// in(206,207,208,209) and operationTask.planFinish<? ) )");
			// hql.append(" and operationTask.device.criticalLevel<4");

		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public CheckTask getFirstCheckTask1(String taskUid) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public CheckTask getFirstCheckTask2(String taskUid) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public CheckTask getFirstCheckTask3(String taskUid) throws Exception {
		CheckTask checkTask = null;
		try {
			Session session = this.getSession();
			Criteria crit = session.createCriteria(CheckTask.class);
			crit.add(Restrictions.eq("taskUid", taskUid));
			crit.add(Restrictions.eq("checkTaskType", CheckTask.CHECKTASKTYPE_THIRDCHECK));
			// 三检任务可能会多次产生
			crit.add(Restrictions.lt("checkTaskState", CheckTask.CHECKTASKSTATE_COMPLETED));
			crit.setMaxResults(1);

			checkTask = (CheckTask) crit.uniqueResult();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return checkTask;

	}

	@Override
	public List<CheckTask> getFirstCheckTasks(String taskUid) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public CheckTask getOperationCheckTask(String taskUid) throws Exception {
		CheckTask checkTask = null;
		try {
			Session session = this.getSession();
			Criteria crit = session.createCriteria(CheckTask.class);
			crit.add(Restrictions.eq("taskUid", taskUid));
			crit.add(Restrictions.eq("checkTaskType", CheckTask.CHECKTASKTYPE_OPERATIONCHECK));
			crit.setMaxResults(1);
			checkTask = (CheckTask) crit.uniqueResult();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return checkTask;
	}

	@Override
	public CheckTask getSummaryCheckTask(String taskUid) throws Exception {
		CheckTask checkTask = null;
		try {
			Session session = this.getSession();
			Criteria crit = session.createCriteria(CheckTask.class);
			crit.add(Restrictions.eq("taskUid", taskUid));
			crit.add(Restrictions.eq("checkTaskType", CheckTask.CHECKTASKTYPE_SUMMARYCHECK));
			crit.add(Restrictions.lt("checkTaskState", CheckTask.CHECKTASKSTATE_COMPLETED));
			crit.setMaxResults(1);
			checkTask = (CheckTask) crit.uniqueResult();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return checkTask;
	}

	@Override
	public List<CheckTask> getUnFinishCheckTasks(String partUid, String batchNum, String checkDeptUid) {
		List list = null;
		try {
			Session session = this.getSession();
			StringBuilder hql = new StringBuilder();
			hql.append(" from " + CheckTask.class.getName() + " where ");
			// 流动检验，任务状态为已开始，已暂停
			hql.append("checkTaskState<209  and operationTask.partUid=? and  operationTask.batchNum=?  ");
			hql.append("and  checkDeptUid like ? || '%' ");
			hql.append(" order by operationTask.operationId,checkTaskType");
			Query query = session.createQuery(hql.toString());
			query.setString(0, partUid);
			query.setString(1, batchNum);
			query.setString(2, checkDeptUid);
			list = query.list();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public CheckTask getDeviceFirstCheckTask3(String deviceUid, String operationUid) throws Exception {
		CheckTask checkTask = null;
		try {
			Session session = this.getSession();
			Criteria crit = session.createCriteria(CheckTask.class);
			// 必须写一个别名
			crit.createAlias("operationTask", "op");
			crit.add(Restrictions.lt("checkTaskState", CheckTask.CHECKTASKSTATE_COMPLETED));
			crit.add(Restrictions.eq("checkTaskType", CheckTask.CHECKTASKTYPE_THIRDCHECK));
			crit.add(Restrictions.eq("op.deviceUid", deviceUid));
			crit.add(Restrictions.lt("op.taskState", OperationTask.TASKSTATE_COMPLETED));
			crit.add(Restrictions.eq("op.operationUid", operationUid));
			crit.addOrder(Order.desc("createTime"));
			crit.setMaxResults(1);
			checkTask = (CheckTask) crit.uniqueResult();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return checkTask;
	}

	@Override
	public List<CheckTask> getUnDispatchCheckTasks(String deptUid, Page<CheckTask> page) {
		List list = null;
		try {
			DetachedCriteria crit = DetachedCriteria.forClass(CheckTask.class);
			crit.add(Restrictions.eq("checkTaskState", CheckTask.CHECKTASKSTATE_READY));
			crit.add(Restrictions.like("checkDeptUid", deptUid, MatchMode.END));
			crit.addOrder(Property.forName("actualSend").asc());
			if (page != null) {
				this.pagingQuery(page, crit);
			} else {
				list = this.query(crit, null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public List<CheckTask> getUnRegisterCheckTasksByDevice(String deviceUid, Page<CheckTask> page) {
		List list = null;
		try {
			Session session = this.getSession();
			Criteria crit = session.createCriteria(CheckTask.class);
			// 必须写一个别名
			crit.createAlias("operationTask", "op");
			crit.add(Restrictions.lt("checkTaskState", CheckTask.CHECKTASKSTATE_READY));
			crit.add(Restrictions.eq("checkTaskType", CheckTask.CHECKTASKTYPE_THIRDCHECK));
			crit.add(Restrictions.eq("op.taskState", OperationTask.TASKSTATE_STARTED));
			crit.add(Restrictions.eq("op.deviceUid", deviceUid));
			crit.addOrder(Order.desc("createTime"));

			list = crit.list();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;

	}

	@Override
	public List<CheckTask> getFinishedCheckTasks(String deptUid, Date afterDate, Page<CheckTask> page) {
		List list = null;

		try {
			Session session = this.getSession();
			Criteria crit = session.createCriteria(CheckTask.class);

			crit.add(Restrictions.eq("checkTaskState", CheckTask.CHECKTASKSTATE_COMPLETED));
			// 暂时只显示首件计量任
			// todo
			// lqm
			// crit.add(Restrictions.eq("checkTaskType",
			// CheckTask.FIRSTCHECK_THIRD_TASK));

			crit.add(Restrictions.eq("checkDeptUid", deptUid));

			if (afterDate == null) {
				Calendar calendar = Calendar.getInstance();
				calendar.add(Calendar.DATE, -1);
				afterDate = calendar.getTime();
			}
			crit.add(Restrictions.gt("actualFinish", afterDate));

			// 按照送料时间排序
			crit.addOrder(Order.desc("actualFinish"));

			list = crit.list();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public List<CheckTask> getStartingCheckTasks(String deptUid, Page<CheckTask> page) {
		List list = null;
		try {
			DetachedCriteria crit = DetachedCriteria.forClass(CheckTask.class);
			crit.add(Restrictions.eq("checkTaskState", CheckTask.CHECKTASKSTATE_STARTED));
			crit.add(Restrictions.like("checkDeptUid", deptUid, MatchMode.END));
			crit.addOrder(Order.desc("actualStart"));
			if (page != null) {
				this.pagingQuery(page, crit);
			} else {
				list = this.query(crit, null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public List<CheckTask> getWaitingFirstCheckTasks(String deptUid, Page<CheckTask> page) {
		List list = null;
		try {
			DetachedCriteria crit = DetachedCriteria.forClass(CheckTask.class);
			crit.createAlias("operationTask", "t");
			crit.add(Restrictions.gt("checkTaskState", CheckTask.CHECKTASKSTATE_DRAG));
			crit.add(Restrictions.lt("checkTaskState", CheckTask.CHECKTASKSTATE_COMPLETED));
			crit.add(Restrictions.eq("checkTaskType", CheckTask.CHECKTASKTYPE_THIRDCHECK));
			crit.add(Restrictions.like("checkDeptUid", deptUid, MatchMode.END));
			crit.add(Restrictions.lt("t.taskState", OperationTask.TASKSTATE_COMPLETED));
			// 按照送料时间排序
			crit.addOrder(Order.desc("actualSend"));
			if (page != null) {
				this.pagingQuery(page, crit);
			} else {
				list = this.query(crit, null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public List<CheckTask> getWaitingCheckTasks(String deptUid, String workCenterUid, String drawingId,
			Page<CheckTask> page) {
		List list = null;

		try {
			Session session = this.getSession();
			Criteria crit = session.createCriteria(CheckTask.class);

			crit.add(Restrictions.or(Restrictions.eq("checkTaskState", CheckTask.CHECKTASKSTATE_READY),
					Restrictions.eq("checkTaskState", CheckTask.CHECKTASKSTATE_DISPATCHED)));
			// 暂时只显示首件计量任务
			// todo
			// lqm
			// crit.add(Restrictions.eq("checkTaskType",
			// CheckTask.FIRSTCHECK_THIRD_TASK));

			crit.add(Restrictions.eq("checkDeptUid", deptUid));

			if (workCenterUid != null && workCenterUid.length() > 0)
				crit.add(Restrictions.eq("checkWorkCenterUid", workCenterUid));

			if (drawingId != null && drawingId.length() > 0) {
				crit.createAlias("operationTask", "ot");
				crit.createAlias("ot.part", "bp");

				crit.add(Restrictions.like("bp.drawingId", drawingId, MatchMode.ANYWHERE).ignoreCase());
			}
			// 按照送料时间排序
			crit.addOrder(Order.desc("actualSend"));

			list = crit.list();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public CheckTask getUnFinishFirstCheckTask3(String taskUid, String checkDeptUid) throws Exception {
		CheckTask checkTask = null;
		try {

			Session session = this.getSession();
			Criteria crit = session.createCriteria(CheckTask.class);
			crit.add(Restrictions.eq("taskUid", taskUid));
			crit.add(Restrictions.eq("checkTaskType", CheckTask.CHECKTASKTYPE_THIRDCHECK));
			if (checkDeptUid != null)
				crit.add(Restrictions.eq("checkDeptUid", checkDeptUid));// 由一个检验部门承制
			// 三检任务可能会多次产生
			crit.add(Restrictions.lt("checkTaskState", CheckTask.CHECKTASKSTATE_COMPLETED));
			crit.setMaxResults(1);

			checkTask = (CheckTask) crit.uniqueResult();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return checkTask;
	}

	@Override
	public CheckTask getUnFinishCheckTask(String taskUid, String checkTaskType, String checkDeptUid,
			String checkWorkCenterUid) throws Exception {
		CheckTask checkTask = null;
		try {

			Session session = this.getSession();
			Criteria crit = session.createCriteria(CheckTask.class);
			crit.add(Restrictions.eq("taskUid", taskUid));
			if (checkTaskType != null)
				crit.add(Restrictions.eq("checkTaskType", checkTaskType));
			if (checkDeptUid != null)
				crit.add(Restrictions.eq("checkDeptUid", checkDeptUid));// 由一个检验部门承制
			if (checkWorkCenterUid != null)
				crit.add(Restrictions.eq("checkWorkCenterUid", checkWorkCenterUid));// 由一个检验中心承制

			// 三检任务可能会多次产生
			crit.add(Restrictions.lt("checkTaskState", CheckTask.CHECKTASKSTATE_COMPLETED));
			crit.setMaxResults(1);

			checkTask = (CheckTask) crit.uniqueResult();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return checkTask;
	}

	@Override
	public List<CheckTask> getUnDispatchCheckTasks(String deptUid, String checkTaskType, String checkWorkCenterUid,
			String drawingId, Page<CheckTask> page) {
		List list = null;
		try {
			DetachedCriteria crit = DetachedCriteria.forClass(CheckTask.class);
			crit.add(Restrictions.eq("checkTaskState", CheckTask.CHECKTASKSTATE_READY));
			crit.add(Restrictions.eq("checkDeptUid", deptUid));// 由一个检验部门承制

			if (checkTaskType != null && checkTaskType.length() > 0)
				crit.add(Restrictions.eq("checkTaskType", checkTaskType));
			if (checkWorkCenterUid != null && checkWorkCenterUid.length() > 0)
				crit.add(Restrictions.eq("checkWorkCenterUid", checkWorkCenterUid));
			if (drawingId != null && drawingId.length() > 0) {
				crit.createAlias("operationTask", "ot");
				crit.createAlias("ot.part", "bp");
				crit.add(Restrictions.like("bp.drawingId", drawingId, MatchMode.ANYWHERE).ignoreCase());
			}

			// 按照送料时间排序
			crit.addOrder(Order.desc("actualSend"));
			if (page != null) {
				this.pagingQuery(page, crit);
			} else {
				list = this.query(crit, null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public List<CheckTask> getUnDispatchCheckTasksByBarCode(String barCode, String checkDeptUid, Page<CheckTask> page) {
		List<CheckTask> list = this.getCheckTasksByBarCode(barCode, checkDeptUid, page);
		List<CheckTask> newList = null;

		if (list != null && list.size() > 0) {
			newList = new ArrayList<CheckTask>();
			for (CheckTask checkTask : list) {
				if (checkTask.getCheckTaskState() != null
						&& checkTask.getCheckTaskState() < CheckTask.CHECKTASKSTATE_DISPATCHED)
					newList.add(checkTask);
			}
		}
		return newList;
	}

	@Override
	public List<CheckTask> getCheckTasksByTask(String taskUid) {
		List<CheckTask> list = null;

		try {
			Session session = this.getSession();
			Criteria crit = session.createCriteria(CheckTask.class);
			crit.add(Restrictions.eq("taskUid", taskUid));
			list = crit.list();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public List<CheckTask> getUnFinishCheckTasksByTask(String taskUid) {
		List<CheckTask> list = null;

		try {
			Session session = this.getSession();
			Criteria crit = session.createCriteria(CheckTask.class);
			crit.add(Restrictions.eq("taskUid", taskUid));
			crit.add(Restrictions.lt("checkTaskState", CheckTask.CHECKTASKSTATE_COMPLETED));

			list = crit.list();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

}
